//
//  SaveImgViewController.m
//  Dispatch
//
//  Created by hyeyeon on 14. 2. 7..
//  Copyright (c) 2014년 hyeyeon. All rights reserved.
//

#import "SaveImgViewController.h"

#define MASKTAG 10
#define REVISON 15
#define LIMITSIZE 100

@interface SaveImgViewController ()

@end

@implementation SaveImgViewController
@synthesize parent;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    self.view.backgroundColor=ColorFromRGB(0x343233);
    [self initCropImgView];
}

-(UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark 이미지 클릭했나 확인하는 함수
-(BOOL)checkClickImage:(UIImageView*)_imageview withTouches:(NSSet *)touches
{
    CGPoint pt = [[touches anyObject] locationInView:_imageview];
    if (pt.x>=0 && pt.x<=_imageview.frame.size.width && pt.y>=0 && pt.y<=_imageview.frame.size.height) {
        return YES;
        
    }
    
    
    
    return NO;
}
-(void)borderImgView:(UIImageView*)_imageView
{
    _imageView.layer.borderWidth = 2.0f;
    CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
    CGFloat values[4] = {((float)((0x44acf3 & 0xFF0000) >> 16))/255.0,((float)((0x44acf3 & 0xFF00) >> 8))/255.0,((float)(0x44acf3 & 0xFF))/255.0, 1.0};
    CGColorRef grey = CGColorCreate(space, values);
    _imageView.layer.borderColor = grey;
    CGColorRelease(grey);
    CGColorSpaceRelease(space);
    
    
}
-(void)moveCropImage:(UIImageView*)backImgView position:(CGPoint)point
{
    //마스크 위치가 왼쪽을 벗어나면
    if (point.x<0) {
        point.x=0;
    }
    
    //마스크 위치가 오른쪽을 벗어나면
    if (point.x+backImgView.frame.size.width>=imageView.frame.size.width) {
        point.x=imageView.frame.size.width-backImgView.frame.size.width;
    }
    
    
    //마스크 위치가 상단을 벗어나면
    if (point.y<0) {
        point.y=0;
    }
    //마스크 위치가 하단을 벗어나면
    if (point.y+backImgView.frame.size.height>=imageView.frame.size.height) {
        point.y=imageView.frame.size.height-backImgView.frame.size.height;
    }
    
    
    backImgView.frame = CGRectMake(point.x, point.y, backImgView.frame.size.width, backImgView.frame.size.height);
    
}



#pragma mark 이미지를 움직이는지 체크 한다
-(void)checklistbtn:(UIImageView*)touchImageView inPoint:(CGPoint)touchPoint
{
    if (touchPoint.x>touchImageView.frame.origin.x-REVISON & touchPoint.x<touchImageView.frame.origin.x+touchImageView.frame.size.width+REVISON & touchPoint.y > touchImageView.frame.origin.y-REVISON & touchPoint.y < touchImageView.frame.origin.y+touchImageView.frame.size.height+REVISON) {
        touchImageView.center=touchPoint;
    }
}
/*
 #pragma mark 터치 움직임
 - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
 {
 CGPoint pt = [[touches anyObject] locationInView:self.view];
 // NSLog(@"pst %f %f",pt.x, pt.y);
 
 [self checklistbtn:imageView inPoint:pt];
 }*/

- (UIImage*)imageByCropping:(UIImage *)imageToCrop toRect:(CGRect)rect
{
    //create a context to do our clipping in
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef currentContext = UIGraphicsGetCurrentContext();
    
  	
    
    
    //create a rect with the size we want to crop the image to
    //the X and Y here are zero so we start at the beginning of our
    //newly created context
    CGRect clippedRect = CGRectMake(0,0, rect.size.width, rect.size.height);
    CGContextClipToRect( currentContext, clippedRect);
    //  CGContextScaleCTM(currentContext, 1.0, -1.0);
    
    //create a rect equivalent to the full size of the image
    //offset the rect by the X and Y we want to start the crop
    //from in order to cut off anything before them
    CGRect drawRect = CGRectMake(rect.origin.x * -1,
                                 rect.origin.y * 1,
                                 imageToCrop.size.width,
                                 imageToCrop.size.height);
    
    CGContextTranslateCTM(currentContext, 0.0, drawRect.size.height);
    CGContextScaleCTM(currentContext, 1.0, -1.0);
    
    //draw the image to our clipped context using our offset rect
    CGContextDrawImage(currentContext, drawRect, imageToCrop.CGImage);
    
    //pull the image from our cropped context
    UIImage *cropped = UIGraphicsGetImageFromCurrentImageContext();
    
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    
    //Note: this is autoreleased
    return cropped;
}
- (void)thisImage:(UIImage *)image hasBeenSavedInPhotoAlbumWithError:(NSError *)error usingContextInfo:(void*)ctxInfo {
    if (error) {
        [self photoMessage:@"사진 보관함 접근이 잠겨 있습니다\n설정-개인정보보호- 사진 항목에서 접근을 허용해 주세요"];
        
        // Do anything needed to handle the error or display it to the user
    } else {
        
        [self photoMessage:NSLocalizedString(@"Saved", @"Saved")];
        
        
        //  AppDelegate  *appdelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
        
        // NSLog(@"성공");
    }
}
-(UIImage*)resizedImage:(UIImage*)inImage  inRect:(CGRect)thumbRect {
    UIGraphicsBeginImageContext(thumbRect.size);
    
    // UIGraphicsBeginImageContext(thumbRect.size);
    //  CGContextRef context = UIGraphicsGetCurrentContext();
    //  CGContextScaleCTM(context, 1.5f, 1.5f);
    // [self.view.layer renderInContext:context];
    //  UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    //  UIGraphicsEndImageContext();
    
    //  return viewImage;
    [inImage drawInRect:thumbRect];
    return UIGraphicsGetImageFromCurrentImageContext();
}
-(void)savePhoto
{
    
    
    
    //잘라낼 영역
    CGRect cropRect = CGRectZero;
    
    
    
    //원본이미지의 크키를 알아내자
    CGSize imageSize = CGSizeZero;
    imageSize.width = imageView.image.size.width;
    imageSize.height = imageView.image.size.height;
    
    
    
    
    //잘라낼 부분 프레임
    UIImageView *maskImage = (UIImageView *)[self.view viewWithTag:MASKTAG];
    
    
    
    
    
    
    
    
    
    
    
    
    cropRect=CGRectMake(floorf(maskImage.frame.origin.x*imagerate), floorf(maskImage.frame.origin.y*imagerate2), floorf(maskImage.frame.size.width*imagerate),
                        floorf(maskImage.frame.size.height*imagerate2));
    
    
    UIImage *saveimage =  [self imageByCropping:imageView.image toRect:cropRect];
    
    UIImageWriteToSavedPhotosAlbum(saveimage, self, @selector(thisImage:hasBeenSavedInPhotoAlbumWithError:usingContextInfo:), NULL);
    
}
#pragma mark 터치영역을 확인하는 함수
-(void)touchCheck:(UIImageView*)touchImageView inPoint:(CGPoint)touchPoint
{
    int returnValue;
    //마스크 뷰..
    NSLog(@"touchImageView x %f y %f",touchPoint.x, touchPoint.y);
    if (touchPoint.x>touchImageView.frame.origin.x-REVISON & touchPoint.x<touchImageView.frame.origin.x+touchImageView.frame.size.width+REVISON & touchPoint.y > touchImageView.frame.origin.y-REVISON & touchPoint.y < touchImageView.frame.origin.y+touchImageView.frame.size.height+REVISON) {
        isTouchIn=YES;
        beganPoint = touchPoint;
        //크롭할 이미지 영역을 클릭한경우
        if(touchPoint.y<=touchImageView.frame.origin.y+15 & touchPoint.y >= touchImageView.frame.origin.y-15)
            returnValue=1;//상단
        else if(touchPoint.x>=touchImageView.frame.origin.x-15 & touchPoint.x <= touchImageView.frame.origin.x+15)
            returnValue=2;//왼쪽라인
        else if(touchPoint.y<=touchImageView.frame.origin.y+touchImageView.frame.size.height+15 & touchPoint.y >= touchImageView.frame.origin.y+touchImageView.frame.size.height-15)
            returnValue=3;//하단..
        else if(touchPoint.x>=touchImageView.frame.origin.x+touchImageView.frame.size.width-15 & touchPoint.x <= touchImageView.frame.origin.x+touchImageView.frame.size.width+15)
            returnValue=4;//오른쪽라인
        else
            returnValue=0;
    }
    else//배경을 클릭한 경우
        returnValue=-1;
    flag = returnValue;
    
    NSLog(@"flag is %d",flag);
    
    
    
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    
    //터치 기준 좌표는 현재 self.view 기준으로 한다
    UIImageView *maskimageview = (UIImageView*)[self.view viewWithTag:MASKTAG];
    
    //0:top 1:left 2:down 3:right 4:image -1:background
    if ([self checkClickImage:topArrowView withTouches:touches]) {
        flag=0;
    }
    else if ([self checkClickImage:leftArrowView withTouches:touches]) {
        flag=1;
    }
    else if ([self checkClickImage:downArrowView withTouches:touches]) {
        flag=2;
    }
    else if ([self checkClickImage:rightArrowView withTouches:touches]) {
        flag=3;
    }
    else if ([self checkClickImage:maskimageview withTouches:touches]) {
        flag=4;
    }
    else
        flag = -1;
    
    beganPoint = [[touches anyObject] locationInView:self.view];
    
    
    return;
}
-(void)resettingArrowFrame
{
    
    UIImageView *maskImgView = (UIImageView *)[self.view viewWithTag:MASKTAG];
    
    
    topArrowView.frame=CGRectMake((maskImgView.frame.size.width-20)/2, -10, 20, 20);
    leftArrowView.frame=CGRectMake(-10, (maskImgView.frame.size.height-20)/2, 20, 20);
    downArrowView.frame=CGRectMake((maskImgView.frame.size.width-20)/2, maskImgView.frame.size.height-10, 20, 20);
    rightArrowView.frame=CGRectMake(maskImgView.frame.size.width-10, (maskImgView.frame.size.height-20)/2, 20, 20);
    
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    CGPoint Position=CGPointZero;
    CGPoint pt=[[touches anyObject] locationInView:self.view];
    UIImageView *maskimageview = (UIImageView *)[self.view viewWithTag:MASKTAG];
    
    Position.x = maskimageview.frame.origin.x+(pt.x-beganPoint.x);
    Position.y = maskimageview.frame.origin.y+(pt.y-beganPoint.y);
    
    
    if (flag==0) {
        //좌표 크기도 달라진다
        CGFloat height = maskimageview.frame.size.height-(pt.y-beganPoint.y);
        if (height<=LIMITSIZE || Position.y<0) {
            return;
        }
        maskimageview.frame=CGRectMake(maskimageview.frame.origin.x, Position.y, maskimageview.frame.size.width, height);
    }
    else if (flag==1) {
        CGFloat width = maskimageview.frame.size.width-(pt.x-beganPoint.x);
        if (width<=LIMITSIZE || Position.x<0) {
            return;
        }
        maskimageview.frame=CGRectMake(Position.x, maskimageview.frame.origin.y, width, maskimageview.frame.size.height);
    }
    else if (flag==2) {
        CGFloat height = maskimageview.frame.size.height+(pt.y-beganPoint.y);
        if (height<=LIMITSIZE || height+maskimageview.frame.origin.y >imageView.frame.size.height) {
            return;
        }
        maskimageview.frame=CGRectMake(maskimageview.frame.origin.x, maskimageview.frame.origin.y, maskimageview.frame.size.width, height);
    }
    else if (flag==3) {
        CGFloat width = maskimageview.frame.size.width+(pt.x-beganPoint.x);
        if (width<=LIMITSIZE || width+maskimageview.frame.origin.x >=imageView.frame.size.width) {
            return;
        }
        maskimageview.frame=CGRectMake(maskimageview.frame.origin.x, maskimageview.frame.origin.y, width, maskimageview.frame.size.height);
    }
    else if(flag==4)
    {
        pt = [[touches anyObject] locationInView:self.view];
        
        Position.x = maskimageview.frame.origin.x+(pt.x-beganPoint.x);
        Position.y = maskimageview.frame.origin.y+(pt.y-beganPoint.y);
        if (Position.x<=0) {
            Position.x=0;
        }
        if (Position.x+maskimageview.frame.size.width>=imageView.frame.size.width) {
            Position.x=maskimageview.frame.origin.x;
        }
        
        if (Position.y<=0) {
            Position.y=0;
        }
        if (Position.y+maskimageview.frame.size.height>=imageView.frame.size.height) {
            Position.y=maskimageview.frame.origin.y;
        }
        
        maskimageview.frame=CGRectMake(Position.x, Position.y, maskimageview.frame.size.width, maskimageview.frame.size.height);
        
        
        
        
        
    }
    else
        return;
    
    
    
    [self resettingArrowFrame];
    beganPoint=pt;
    
    
    
    
    
    
    
    
    
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    /*
     UIImageView *touchImageView =(UIImageView *)[self.view viewWithTag:LISTIMGBTNTAG];
     CGPoint touchPoint = [[touches anyObject] locationInView:self.view];
     // NSLog(@"pst %f %f",pt.x, pt.y);
     
     if (touchPoint.x>touchImageView.frame.origin.x-REVISON & touchPoint.x<touchImageView.frame.origin.x+touchImageView.frame.size.width+REVISON & touchPoint.y > touchImageView.frame.origin.y-REVISON & touchPoint.y < touchImageView.frame.origin.y+touchImageView.frame.size.height+REVISON) {
     //움직임이 없엇을경우에만
     if (!bisTouchMoving) {
     [self listype];
     
     }
     
     
     }
     bisTouchMoving=NO;
     */
    
}
#pragma mark 이미지 크롭에 필요한 뷰를 셋팅한다
-(void)initCropImgView
{
    
    
    
    
    UIImageView *maskImgView =[[UIImageView alloc] initWithFrame:CGRectMake(0, 20, imageView.frame.size.width, imageView.frame.size.height-20)];
    maskImgView.tag=MASKTAG;
    maskImgView.userInteractionEnabled=YES;
    //   maskImgView.backgroundColor=[UIColor redColor];
    // maskImgView.alpha=0.5;
    [self borderImgView:maskImgView];
    
    [imageView addSubview:maskImgView];
    
    
    topArrowView  = [[UIImageView alloc] initWithFrame:CGRectMake((maskImgView.frame.size.width-20)/2, -10, 20, 20)];
    leftArrowView  = [[UIImageView alloc] initWithFrame:CGRectMake(-10, (maskImgView.frame.size.height-20)/2, 20, 20)];
    downArrowView  = [[UIImageView alloc] initWithFrame:CGRectMake((maskImgView.frame.size.width-20)/2, maskImgView.frame.size.height-10, 20, 20)];
    rightArrowView  = [[UIImageView alloc] initWithFrame:CGRectMake(maskImgView.frame.size.width-10, (maskImgView.frame.size.height-20)/2, 20, 20)];
    
    [topArrowView setImage:[UIImage imageNamed:@"icon_editpoint"]];
    [leftArrowView setImage:[UIImage imageNamed:@"icon_editpoint"]];
    
    [downArrowView setImage:[UIImage imageNamed:@"icon_editpoint"]];
    [rightArrowView setImage:[UIImage imageNamed:@"icon_editpoint"]];
    
    [maskImgView addSubview:topArrowView];
    [maskImgView addSubview:leftArrowView];
    [maskImgView addSubview:downArrowView];
    [maskImgView addSubview:rightArrowView];
    
    
    
    
    
    
    
}
-(void)removeModal
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)removeAlertView:(NSTimer*)timer
{
    UIAlertView *backview = (UIAlertView *)[timer userInfo];
    [backview dismissWithClickedButtonIndex:0 animated:YES];
    [self removeModal];
}

-(void)photoMessage:(NSString*)message
{
    
    //팝업뷰 띄우기
    
    NSLog(@"message : %@",message);
    
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:message delegate:nil cancelButtonTitle:nil otherButtonTitles: nil];
    [alertView show];
    
    [NSTimer scheduledTimerWithTimeInterval:1.0 target:self
                                   selector:@selector(removeAlertView:)
                                   userInfo:alertView repeats:NO];
    
    
}

-(void)initSetImage:(UIImage*)_image frame:(CGRect)_frame
{
    if (!imageView) {
        imageView = [[UIImageView alloc] init];
    }
    
    
    
    
    [imageView setImage:_image];
    //저장 취소 버튼을 확보하기 위해...
    
    float HEIGHT = mySize.height-20;
    float WIDTH = mySize.width;
    
    if (_frame.size.height>=HEIGHT-44) {
        //꽉찬하면 아래 여백을 구해야 한다
        CGFloat rate = _frame.size.width/_frame.size.height; //가로 세로 비율
        _frame=CGRectMake(_frame.origin.x, _frame.origin.y, _frame.size.width-(44*rate), _frame.size.height-44);
        
        imageView.frame=CGRectMake((WIDTH-_frame.size.width)/2, ((HEIGHT)-_frame.size.height-44)/2, _frame.size.width, _frame.size.height);
        
    }
    else
    {
        imageView.frame=CGRectMake((WIDTH-_frame.size.width)/2, ((HEIGHT)-_frame.size.height)/2, _frame.size.width, _frame.size.height);
        
    }
    
    imageView.center = CGPointMake(imageView.center.x, (HEIGHT/2)+myOrginY-(34/2));
    
    //비율 얼마 만큼 줄어들었나
    imagerate = _image.size.width/_frame.size.width;
    imagerate2 = _image.size.height/_frame.size.height;
    NSLog(@"imagerate %f %f", imagerate,imagerate2);
    
    
    
    [self.view addSubview:imageView];
    
    
    
    
    //저장 취소 버튼
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [cancelBtn setImage:[UIImage imageNamed:@"btn_cancel"] forState:UIControlStateNormal];
    
    [cancelBtn setImage:[UIImage imageNamed:@"btn_cancel_on"] forState:UIControlStateHighlighted];
    
    
    
    // [cancelBtn setTitle:@"취소" forState:UIControlStateNormal];
    [cancelBtn addTarget:self action:@selector(removeModal) forControlEvents:UIControlEventTouchUpInside];
    cancelBtn.frame=CGRectMake(5, HEIGHT-44+5+myOrginY, 44, 34);
    
    
    UIButton *saveBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    //  [saveBtn setTitle:@"저장" forState:UIControlStateNormal];
    [saveBtn addTarget:self action:@selector(savePhoto) forControlEvents:UIControlEventTouchUpInside];
    saveBtn.frame=CGRectMake(WIDTH-44-5, cancelBtn.frame.origin.y, 44, 34);
    [saveBtn setImage:[UIImage imageNamed:@"btn_confirm"] forState:UIControlStateNormal];
    
    [saveBtn setImage:[UIImage imageNamed:@"btn_confirm_on"] forState:UIControlStateHighlighted];
    
    [self.view addSubview:cancelBtn];
    
    [self.view addSubview:saveBtn];
    
    
    
}

@end
